//
//  SignView.m
//  HGMM
//
//  Created by @HUI on 15/9/21.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "SignView.h"

@interface SignView ()

@property(assign,nonatomic)CGMutablePathRef drawPath;
@property(assign,nonatomic)CGPoint currentPoint;
@property(strong,nonatomic)NSMutableArray*pathArr;
@property(assign,nonatomic)BOOL pathRelease;
@property(strong,nonatomic)UIColor*drawColor;
@property(strong,nonatomic)UIImage* drawImage;

@end

@implementation SignView


-(instancetype)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if(self){
        [self setBackgroundColor:[UIColor whiteColor]];
        self.drawColor=[UIColor blackColor];
        self.lineWidth=2;
    }
    return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context=UIGraphicsGetCurrentContext();
    [self drawView:context];
}

-(void)drawView:(CGContextRef)context{
    for(UIBezierPath *path in self.pathArr){
        CGContextAddPath(context, path.CGPath);
        [self.drawColor set];
        CGContextSetLineWidth(context, path.lineWidth);
        CGContextSetLineCap(context, kCGLineCapRound);
        CGContextDrawPath(context, kCGPathStroke);
    }
    if(!self.pathRelease){
        CGContextAddPath(context, self.drawPath);
        [self.drawColor set];
        CGContextSetLineCap(context, kCGLineCapRound);
        CGContextSetLineWidth(context, self.lineWidth);
        //CGContextDrawPath(context, kCGPathStroke);
        CGContextStrokePath(context);
    }
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch*touch=[touches anyObject];
    self.currentPoint=[touch locationInView:self];
    _drawPath=CGPathCreateMutable();
    self.pathRelease=NO;
    CGPathMoveToPoint(self.drawPath, nil, self.currentPoint.x, self.currentPoint.y);
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch*touch=[touches anyObject];
    self.currentPoint=[touch locationInView:self];
    CGPathAddLineToPoint(self.drawPath, nil, self.currentPoint.x, self.currentPoint.y);
    [self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    if(!self.pathArr){
        self.pathArr=[NSMutableArray array];
    }
    UIBezierPath* path=[UIBezierPath bezierPathWithCGPath:self.drawPath];
    path.lineWidth = self.lineWidth;
    [self.pathArr addObject:path];
    CGPathRelease(_drawPath);
    self.pathRelease=YES;
}
-(void)undo{
    [self.pathArr removeLastObject];
    [self setNeedsDisplay];
}
-(void)clearScreen{
    [self.pathArr removeAllObjects];
    [self setNeedsDisplay];
}


@end
